'use strict';

exports.main = async (event, context) => {
  console.log('云函数接收到的完整参数:', event);
  const { action, ...params } = event;
  
  console.log('解析的action:', action);
  console.log('解析的params:', params);
  
  try {
    switch(action) {
      case 'getUserPoints':
        return await getUserPoints(params, context);
      case 'adjustUserPoints':
        console.log('✅ 正在执行 adjustUserPoints 分支');
        return await adjustUserPoints(params, context);
      case 'getUserHistory':
        return await getUserHistory(params, context);
      case 'batchAdjustPoints':
        return await batchAdjustPoints(params, context);
      case 'initUserPoints':
        return await initUserPoints(params, context);
      case 'resetUserPoints':
        return await resetUserPoints(params, context);
      case 'debugDatabase':
        return await debugDatabase(params, context);
      default:
        return { code: 400, msg: '不支持的操作' };
    }
  } catch(e) {
    console.error('云函数执行错误:', e);
    return { code: 500, msg: e.message || '服务器内部错误' };
  }
};

// 获取用户积分信息
async function getUserPoints(params, context) {
  try {
    console.log('开始获取用户积分信息...');
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    const userPointsCollection = db.collection('user_points');
    const userScoreCollection = db.collection('user-score');
    
    // 获取用户基本信息
    console.log('查询用户基本信息...');
    const usersResult = await usersCollection
      .field({
        username: true,
        nickname: true,
        credit_score: true,
        create_date: true,
        status: true
      })
      .orderBy('create_date', 'desc')
      .get();
    
    const users = usersResult.data || [];
    console.log(`找到 ${users.length} 个用户`);
    
    // 检查是否有user_points表的数据
    console.log('检查user_points表...');
    const allPointsResult = await userPointsCollection.limit(5).get();
    console.log(`user_points表中有 ${allPointsResult.data ? allPointsResult.data.length : 0} 条记录`);
    
    // 检查是否有user-score表的数据
    console.log('检查user-score表...');
    const allScoreResult = await userScoreCollection.limit(5).get();
    console.log(`user-score表中有 ${allScoreResult.data ? allScoreResult.data.length : 0} 条记录`);
    
    // 为每个用户获取积分信息和最近变动
    for (let user of users) {
      try {
        console.log(`处理用户: ${user.username} (${user._id})`);
        
        // 计算用户的实际总积分（基于user-score历史记录）
        console.log(`📊 开始计算用户 ${user.username} (${user._id}) 的总积分...`);
        
        // 首先检查 user-score 表是否存在数据
        const allScoreResult = await userScoreCollection
          .where({
            user_id: user._id
          })
          .get();
        
        console.log(`📊 用户 ${user.username} 的积分查询结果:`, {
          success: allScoreResult.success,
          total: allScoreResult.total,
          dataLength: allScoreResult.data ? allScoreResult.data.length : 0
        });
        
        let totalPoints = 0;
        if (allScoreResult.data && allScoreResult.data.length > 0) {
          console.log(`📊 用户 ${user.username} 有 ${allScoreResult.data.length} 条积分记录:`);
          allScoreResult.data.forEach((record, index) => {
            console.log(`  ${index + 1}. 积分: ${record.score}, 类型: ${record.type}, 时间: ${new Date(record.create_time).toLocaleString()}`);
            totalPoints += (record.score || 0);
          });
          console.log(`📊 用户 ${user.username} 计算出的总积分: ${totalPoints}`);
        } else {
          console.log(`📊 用户 ${user.username} 没有积分变动记录，总积分为0`);
          
          // 检查是否是因为数据库查询失败
          if (!allScoreResult.success) {
            console.error(`❌ 查询用户 ${user.username} 积分记录失败:`, allScoreResult);
          }
        }
        
        // 设置计算后的积分
        user.points = Math.max(0, totalPoints); // 确保不为负数
        user.total_points = Math.max(0, totalPoints);
        
        // 获取或创建user_points记录以获取其他信息
        const pointsResult = await userPointsCollection
          .where({
            user_id: user._id
          })
          .get();
        
        if (pointsResult.data && pointsResult.data.length > 0) {
          const pointsData = pointsResult.data[0];
          user.used_points = pointsData.used_points || 0;
          const levelInfo = calculateUserLevel(totalPoints);
          user.current_level = pointsData.current_level || levelInfo.level;
          user.level_name = pointsData.level_name || levelInfo.name;
          user.continuous_days = pointsData.continuous_days || 0;
          
          // 更新user_points表中的积分值
          await userPointsCollection.doc(pointsData._id).update({
            total_points: totalPoints,
            available_points: totalPoints,
            current_level: levelInfo.level,
            level_name: levelInfo.name,
            update_time: new Date()
          });
          
        } else {
          // 如果没有积分记录，创建一个新记录
          console.log(`用户 ${user.username} 没有积分记录，创建新记录...`);
          const levelInfo = calculateUserLevel(totalPoints);
          
          try {
            const defaultPoints = {
              user_id: user._id,
              total_points: totalPoints,
              available_points: totalPoints,
              used_points: 0,
              current_level: levelInfo.level,
              level_name: levelInfo.name,
              continuous_days: 0,
              create_time: new Date(),
              update_time: new Date()
            };
            
            await userPointsCollection.add(defaultPoints);
            user.used_points = 0;
            user.current_level = levelInfo.level;
            user.level_name = levelInfo.name;
            user.continuous_days = 0;
            console.log(`为用户 ${user.username} 创建了积分记录，总积分: ${totalPoints}`);
          } catch(createError) {
            console.log(`创建积分记录失败:`, createError);
            // 设置默认值
            user.used_points = 0;
            const fallbackLevelInfo = calculateUserLevel(totalPoints);
            user.current_level = fallbackLevelInfo.level;
            user.level_name = fallbackLevelInfo.name;
            user.continuous_days = 0;
          }
        }
        
        // 获取最近的积分变动记录
        // 注意：不在数据库层面排序，而是获取所有记录后在JS层面排序，避免字符串/数值混合导致的排序错误
        const recentScoreResult = await userScoreCollection
          .where({
            user_id: user._id
          })
          .get();
        
        if (recentScoreResult.data && recentScoreResult.data.length > 0) {
          // 在JavaScript层面按时间戳排序（确保数值比较）
          const sortedRecords = recentScoreResult.data.sort((a, b) => {
            const timeA = Number(a.create_time) || 0;
            const timeB = Number(b.create_time) || 0;
            return timeB - timeA; // 降序，最新的在前
          });
          
          const scoreData = sortedRecords[0];
          console.log(`📌 用户 ${user.username} 最近变动:`, {
            总记录数: recentScoreResult.data.length,
            时间戳: scoreData.create_time,
            时间戳类型: typeof scoreData.create_time,
            时间: new Date(Number(scoreData.create_time)).toLocaleString(),
            积分: scoreData.score,
            类型: scoreData.type,
            原因: scoreData.reason || getScoreTypeDesc(scoreData.type)
          });
          
          user.last_change = {
            amount: scoreData.score,
            reason: scoreData.reason || getScoreTypeDesc(scoreData.type),
            description: scoreData.description || '',
            time: Number(scoreData.create_time) // 确保是数值类型
          };
        }
        
        // 设置信用分默认值
        if (!user.credit_score) {
          user.credit_score = 100;
        }
        
      } catch(e) {
        console.error(`获取用户 ${user._id} 积分信息失败:`, e);
        // 设置默认值
        user.points = 0;
        user.total_points = 0;
        user.credit_score = user.credit_score || 100;
        user.current_level = 1;
        user.level_name = '新手';
      }
    }
    
    console.log('用户积分信息获取完成，返回数据...');
    return {
      code: 0,
      data: users,
      msg: '获取用户积分信息成功'
    };
  } catch(e) {
    console.error('获取用户积分信息失败:', e);
    return { code: 500, msg: '获取用户积分信息失败: ' + e.message };
  }
}

// 积分类型描述映射
function getScoreTypeDesc(type) {
  const typeMap = {
    'post_pin': '帖子置顶',
    'post_like': '帖子获赞',
    'comment_like': '评论获赞',
    'daily_sign': '每日签到',
    'activity_create': '活动创建',
    'activity_join': '活动参与',
    'task-finished': '任务完成',
    'task-review': '任务评价',
    'manual_adjust': '管理员调整',
    'credit_adjust': '信用分调整'
  };
  return typeMap[type] || '系统调整';
}

// 调整用户积分/信用分
async function adjustUserPoints(params, context) {
  console.log('🎯 adjustUserPoints 函数开始执行');
  console.log('🎯 接收到的参数:', params);
  
  const { userId, type, adjustAction, amount, reason, note, operator } = params;
  
  console.log('🎯 解构后的参数值:');
  console.log('  userId:', userId);
  console.log('  type:', type);
  console.log('  adjustAction:', adjustAction);
  console.log('  amount:', amount);
  console.log('  reason:', reason);
  
  console.log('开始执行积分调整，参数:', params);
  
  // 详细的参数验证
  const missingParams = [];
  if (!userId) missingParams.push('userId');
  if (!type) missingParams.push('type');
  if (!adjustAction) missingParams.push('adjustAction');
  if (amount === undefined || amount === null || amount === '') missingParams.push('amount');
  if (!reason) missingParams.push('reason');
  
  if (missingParams.length > 0) {
    console.log('参数验证失败，缺少参数:', missingParams);
    console.log('具体参数值:', {
      userId: userId,
      type: type,
      adjustAction: adjustAction,
      amount: amount,
      reason: reason,
      note: note,
      operator: operator
    });
    return { code: 400, msg: `参数不完整：缺少 ${missingParams.join(', ')}` };
  }
  
  // 验证数值参数
  const adjustAmount = parseInt(amount);
  if (isNaN(adjustAmount) || adjustAmount <= 0) {
    return { code: 400, msg: '调整数量必须是大于0的整数' };
  }
  
  // 验证调整类型
  if (!['points', 'credit'].includes(type)) {
    return { code: 400, msg: '调整类型无效，只支持points或credit' };
  }
  
  // 验证操作类型
  if (!['add', 'subtract'].includes(adjustAction)) {
    return { code: 400, msg: '操作类型无效，只支持add或subtract' };
  }
  
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    const userPointsCollection = db.collection('user_points');
    const userScoreCollection = db.collection('user-score');
    
    console.log(`查询用户信息: ${userId}`);
    
    // 获取用户当前信息
    const userResult = await usersCollection.doc(userId).get();
    if (!userResult.data || userResult.data.length === 0) {
      console.log('用户不存在');
      return { code: 404, msg: '用户不存在' };
    }
    
    const user = userResult.data[0];
    const finalAdjustAmount = adjustAction === 'add' ? adjustAmount : -adjustAmount;
    
    console.log(`用户信息: ${user.username}, 调整类型: ${type}, 调整操作: ${adjustAction}, 调整量: ${finalAdjustAmount}`);
    
    if (type === 'points') {
      // 处理积分调整
      console.log('开始处理积分调整...');
      let userPointsData = null;
      
      // 获取或创建用户积分记录
      const pointsResult = await userPointsCollection.where({ user_id: userId }).get();
      if (pointsResult.data && pointsResult.data.length > 0) {
        userPointsData = pointsResult.data[0];
        console.log(`找到用户积分记录: 当前积分 ${userPointsData.available_points}`);
      } else {
        console.log('用户积分记录不存在，创建新记录...');
        // 创建新的积分记录
        const newPointsData = {
          user_id: userId,
          total_points: 0,
          available_points: 0,
          used_points: 0,
          current_level: 1,
          level_name: '新手',
          continuous_days: 0,
          create_time: new Date(),
          update_time: new Date()
        };
        const createResult = await userPointsCollection.add(newPointsData);
        userPointsData = { ...newPointsData, _id: createResult.id };
        console.log('创建用户积分记录成功');
      }
      
      const oldPoints = userPointsData.available_points || 0;
      
      // 计算新的积分值
      const newAvailablePoints = Math.max(0, oldPoints + finalAdjustAmount);
      const newTotalPoints = Math.max(newAvailablePoints, userPointsData.total_points || 0);
      
      // 检查扣除操作是否会导致积分不足
      if (adjustAction === 'subtract' && oldPoints < adjustAmount) {
        console.log(`积分不足: 当前积分 ${oldPoints}, 尝试扣除 ${adjustAmount}`);
        return { 
          code: 400, 
          msg: `积分不足，当前积分：${oldPoints}，尝试扣除：${adjustAmount}` 
        };
      }
      
      // 根据积分计算等级
      const levelInfo = calculateUserLevel(newTotalPoints);
      
      console.log(`积分调整: ${oldPoints} -> ${newAvailablePoints}, 等级: ${levelInfo.name}`);
      
      // 更新积分记录
      await userPointsCollection.doc(userPointsData._id).update({
        available_points: newAvailablePoints,
        total_points: newTotalPoints,
        current_level: levelInfo.level,
        level_name: levelInfo.name,
        update_time: new Date()
      });
      
      // 记录积分变动历史
      const now = Date.now();
      await userScoreCollection.add({
        user_id: userId,
        score: finalAdjustAmount,
        type: 'manual_adjust',
        description: `管理员${operator || '系统'}调整：${reason}${note ? ' - ' + note : ''}`,
        related_id: '',
        create_time: now,
        operator: operator || '系统管理员',
        note: note || '',
        reason: reason
      });
      
      console.log(`📝 积分变动记录已添加，时间戳: ${now} (${new Date(now).toLocaleString()})`);
      
      console.log('积分调整完成');
      
      return {
        code: 0,
        data: {
          userId: userId,
          type: type,
          oldValue: oldPoints,
          newValue: newAvailablePoints,
          level: levelInfo
        },
        msg: `积分调整成功：${adjustAction === 'add' ? '增加' : '扣除'}${adjustAmount}积分`
      };
      
    } else if (type === 'credit') {
      // 处理信用分调整
      console.log('开始处理信用分调整...');
      const currentCredit = user.credit_score || 100;
      
      // 检查扣除操作是否会导致信用分不足
      if (adjustAction === 'subtract' && currentCredit < adjustAmount) {
        console.log(`信用分不足: 当前信用分 ${currentCredit}, 尝试扣除 ${adjustAmount}`);
        return { 
          code: 400, 
          msg: `信用分不足，当前信用分：${currentCredit}，尝试扣除：${adjustAmount}` 
        };
      }
      
      // 计算新的信用分，确保在0-100范围内
      const newCredit = Math.max(0, Math.min(100, currentCredit + finalAdjustAmount));
      
      console.log(`信用分调整: ${currentCredit} -> ${newCredit}`);
      
      // 更新用户信用分
      await usersCollection.doc(userId).update({
        credit_score: newCredit
      });
      
      // 记录信用分变动历史
      const now = Date.now();
      await userScoreCollection.add({
        user_id: userId,
        score: finalAdjustAmount,
        type: 'credit_adjust',
        description: `管理员${operator || '系统'}调整：${reason}${note ? ' - ' + note : ''}`,
        related_id: '',
        create_time: now,
        operator: operator || '系统管理员',
        note: note || '',
        reason: reason
      });
      
      console.log(`📝 信用分变动记录已添加，时间戳: ${now} (${new Date(now).toLocaleString()})`);
      
      console.log('信用分调整完成');
      
      return {
        code: 0,
        data: {
          userId: userId,
          type: type,
          oldValue: currentCredit,
          newValue: newCredit
        },
        msg: `信用分调整成功：${adjustAction === 'add' ? '增加' : '扣除'}${adjustAmount}分`
      };
    }
    
    return { code: 400, msg: '不支持的调整类型' };
    
  } catch(e) {
    console.error('调整用户积分失败:', e);
    return { code: 500, msg: '调整用户积分失败: ' + e.message };
  }
}

// 根据积分计算用户等级
function calculateUserLevel(totalPoints) {
  if (totalPoints >= 10000) return { level: 7, name: 'VIP钻石' };
  if (totalPoints >= 5000) return { level: 6, name: 'VIP黄金' };
  if (totalPoints >= 2000) return { level: 5, name: 'VIP白银' };
  if (totalPoints >= 1000) return { level: 4, name: 'VIP' };
  if (totalPoints >= 500) return { level: 3, name: '高级' };
  if (totalPoints >= 200) return { level: 2, name: '中级' };
  return { level: 1, name: '新手' };
}

// 获取用户历史记录
async function getUserHistory(params, context) {
  const { userId } = params;
  
  if (!userId) {
    return { code: 400, msg: '用户ID不能为空' };
  }
  
  try {
    const db = uniCloud.database();
    const userScoreCollection = db.collection('user-score');
    
    // 获取所有积分变动记录
    const allHistory = await userScoreCollection
      .where({
        user_id: userId
      })
      .orderBy('create_time', 'desc')
      .limit(100)
      .get();
    
    const historyData = allHistory.data || [];
    
    // 分离积分记录和信用分记录
    const pointsHistory = [];
    const creditHistory = [];
    
    historyData.forEach(record => {
      const historyItem = {
        _id: record._id,
        amount: record.score,
        reason: getScoreTypeDesc(record.type),
        note: record.description || '',
        create_time: record.create_time,
        operator: record.type === 'manual_adjust' || record.type === 'credit_adjust' ? '管理员' : '系统',
        type: record.type
      };
      
      if (record.type === 'credit_adjust') {
        creditHistory.push(historyItem);
      } else {
        pointsHistory.push(historyItem);
      }
    });
    
    return {
      code: 0,
      pointsHistory: pointsHistory,
      creditHistory: creditHistory,
      msg: '获取历史记录成功'
    };
  } catch(e) {
    console.error('获取用户历史记录失败:', e);
    return { code: 500, msg: '获取用户历史记录失败: ' + e.message };
  }
}

// 批量调整积分
async function batchAdjustPoints(params, context) {
  const { userIds, type, action, amount, reason, note, operator } = params;
  
  if (!userIds || !Array.isArray(userIds) || userIds.length === 0) {
    return { code: 400, msg: '用户列表不能为空' };
  }
  
  if (!type || !action || !amount || !reason) {
    return { code: 400, msg: '参数不完整' };
  }
  
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    const historyCollection = db.collection('user_points_history');
    
    const adjustAmount = action === 'add' ? amount : -amount;
    let successCount = 0;
    let failCount = 0;
    
    for (let userId of userIds) {
      try {
        // 获取用户当前信息
        const userResult = await usersCollection.doc(userId).get();
        if (!userResult.data || userResult.data.length === 0) {
          failCount++;
          continue;
        }
        
        const user = userResult.data[0];
        let updateData = {};
        let newValue = 0;
        
        if (type === 'points') {
          newValue = Math.max(0, (user.points || 0) + adjustAmount);
          updateData.points = newValue;
        } else if (type === 'credit') {
          newValue = Math.max(0, Math.min(100, (user.credit_score || 100) + adjustAmount));
          updateData.credit_score = newValue;
        }
        
        // 更新用户数据
        await usersCollection.doc(userId).update(updateData);
        
        // 记录历史
        await historyCollection.add({
          user_id: userId,
          username: user.username,
          type: type,
          amount: adjustAmount,
          reason: reason,
          note: note || '',
          operator: operator || '系统',
          before_value: type === 'points' ? (user.points || 0) : (user.credit_score || 100),
          after_value: newValue,
          create_time: Date.now()
        });
        
        successCount++;
      } catch(e) {
        console.error(`调整用户 ${userId} 失败:`, e);
        failCount++;
      }
    }
    
    return {
      code: 0,
      data: {
        successCount: successCount,
        failCount: failCount,
        total: userIds.length
      },
      msg: `批量调整完成，成功 ${successCount} 个，失败 ${failCount} 个`
    };
  } catch(e) {
    console.error('批量调整积分失败:', e);
    return { code: 500, msg: '批量调整积分失败: ' + e.message };
  }
}

// 初始化用户积分数据
async function initUserPoints(params, context) {
  try {
    console.log('开始初始化用户积分数据...');
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    const userPointsCollection = db.collection('user_points');
    
    // 获取所有用户
    const usersResult = await usersCollection.get();
    const users = usersResult.data || [];
    console.log(`找到 ${users.length} 个用户需要初始化`);
    
    let initCount = 0;
    let skipCount = 0;
    
    for (let user of users) {
      try {
        // 检查用户是否已有积分记录
        const existingPoints = await userPointsCollection
          .where({ user_id: user._id })
          .get();
        
        if (existingPoints.data && existingPoints.data.length > 0) {
          console.log(`用户 ${user.username} 已有积分记录，跳过`);
          skipCount++;
          continue;
        }
        
        // 创建默认积分记录
        const defaultPoints = {
          user_id: user._id,
          total_points: 0,
          available_points: 0,
          used_points: 0,
          current_level: 1,
          level_name: '新手',
          continuous_days: 0,
          create_time: new Date(),
          update_time: new Date()
        };
        
        await userPointsCollection.add(defaultPoints);
        console.log(`为用户 ${user.username} 创建积分记录`);
        initCount++;
        
      } catch(e) {
        console.error(`初始化用户 ${user.username} 积分失败:`, e);
      }
    }
    
    return {
      code: 0,
      data: {
        totalUsers: users.length,
        initCount: initCount,
        skipCount: skipCount
      },
      msg: `初始化完成：新建 ${initCount} 个积分记录，跳过 ${skipCount} 个已有记录`
    };
    
  } catch(e) {
    console.error('初始化用户积分数据失败:', e);
    return { code: 500, msg: '初始化失败: ' + e.message };
  }
}

// 重置用户积分数据（清空重建）
async function resetUserPoints(params, context) {
  try {
    console.log('开始重置用户积分数据...');
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    const userPointsCollection = db.collection('user_points');
    
    // 清空现有积分记录
    console.log('清空现有积分记录...');
    await userPointsCollection.where({}).remove();
    
    // 获取所有用户
    const usersResult = await usersCollection.get();
    const users = usersResult.data || [];
    console.log(`找到 ${users.length} 个用户需要重置`);
    
    let resetCount = 0;
    
    for (let user of users) {
      try {
        // 创建新的积分记录
        const newPointsData = {
          user_id: user._id,
          total_points: 0,
          available_points: 0,
          used_points: 0,
          current_level: 1,
          level_name: '新手',
          continuous_days: 0,
          create_time: new Date(),
          update_time: new Date()
        };
        
        await userPointsCollection.add(newPointsData);
        console.log(`重置用户 ${user.username} 积分记录`);
        resetCount++;
        
      } catch(e) {
        console.error(`重置用户 ${user.username} 积分失败:`, e);
      }
    }
    
    return {
      code: 0,
      data: {
        totalUsers: users.length,
        resetCount: resetCount
      },
      msg: `重置完成：成功重置 ${resetCount} 个用户的积分记录`
    };
    
  } catch(e) {
    console.error('重置用户积分数据失败:', e);
    return { code: 500, msg: '重置失败: ' + e.message };
  }
}

// 调试数据库状态
async function debugDatabase(params, context) {
  try {
    console.log('开始调试数据库状态...');
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    const userPointsCollection = db.collection('user_points');
    const userScoreCollection = db.collection('user-score');
    
    // 检查用户表
    const usersResult = await usersCollection.limit(10).get();
    const usersCount = usersResult.data ? usersResult.data.length : 0;
    
    // 检查积分表
    const pointsResult = await userPointsCollection.limit(10).get();
    const pointsCount = pointsResult.data ? pointsResult.data.length : 0;
    const pointsData = pointsResult.data || [];
    
    // 检查积分历史表
    const scoreResult = await userScoreCollection.limit(10).get();
    const scoreCount = scoreResult.data ? scoreResult.data.length : 0;
    
    // 分析积分数据
    const pointsAnalysis = pointsData.map(p => ({
      user_id: p.user_id,
      available_points: p.available_points,
      total_points: p.total_points,
      level_name: p.level_name
    }));
    
    return {
      code: 0,
      data: {
        tables: {
          'uni-id-users': {
            count: usersCount,
            status: usersCount > 0 ? 'OK' : 'EMPTY'
          },
          'user_points': {
            count: pointsCount,
            status: pointsCount > 0 ? 'OK' : 'EMPTY',
            sample: pointsAnalysis.slice(0, 3)
          },
          'user-score': {
            count: scoreCount,
            status: scoreCount > 0 ? 'OK' : 'EMPTY'
          }
        },
        timestamp: new Date().toISOString()
      },
      msg: '数据库状态检查完成'
    };
    
  } catch(e) {
    console.error('调试数据库失败:', e);
    return { code: 500, msg: '调试失败: ' + e.message };
  }
}
